import API_BASE_URL from '../config/config';

var subDomain = '-';
let baseURL = API_BASE_URL.baseURL

const api = (url, needSubDomain, method, data) => {
  // console.log(url,needSubDomain,method,data); 

  var _url = baseURL + (needSubDomain ? '/' + subDomain : '') + url;
  let Authorization = null;
  if (url === "/wx/wx/getUserInfoByCode" || url === "/app/menu/getAppResource") {
    Authorization = wx.getStorageSync('token')
  } else {
    if (wx.getStorageSync('token')) {
      Authorization = "Bearer " + JSON.parse(wx.getStorageSync('token'))
    }

    if (url === "/app/mineinfo/getList" || url === "/wx/wx/register") {
      Authorization = ""
    }

  }  

  var header = {
    'Content-Type': 'application/json',
    'Authorization': Authorization
  };
  return new Promise(function (resolve, reject) {

    wx.request({
      url: _url,
      method: method,
      data: data,
      header: header,
      success: function success(request) {
        if (request.data.code == 401) {
          wx.redirectTo({
            url: '/pages/login/login',
          })
          resolve(request.data)
        } else {
          resolve(request.data);
        }
      },
      fail: function fail(error) {
        wx.showToast({
          title: '网络请求超时',
          icon: 'none'
        })
        console.log(error);
        reject(error);
      },
      complete: function complete(aaa) {
        // 加载完成

      }
    });
  }).catch(e=>{
    
  })
};




export const get = (url, data = {}) => {
  return api(url, false, "get", data);
}

export const post = (url, data = {}) => {
  return api(url, false, "post", data);
}

export const put = (url, data = {}) => {
  return api(url, false, "put", data);
}

export const postList = (url, data = []) => {
  return api(url, false, "post", data);
}